import os
import sys
from dotenv import load_dotenv, find_dotenv
from lib.FS import FS_APP, FS_Table

# 这是一个测试用的示例代码，你可以根据自己的需求进行修改。
# 仓库地址https://github.com/ddddnet/FeiShuDataBase

APP_TOKEN = "AmwObPpUAawxRJsQy8BcxRTHn8c"  # 多维表格ID
# TABLE_ID = "tbl9z9aZf6krBhbs"  # 数据表ID
TABLE_ID = "tblVfHNB1Z3CGjcF"


# 从 .env 文件加载环境变量参数
load_dotenv(find_dotenv())

# 获取环境变量
APP_ID = os.getenv("APP_ID")
APP_SECRET = os.getenv("APP_SECRET")


app = FS_APP(APP_ID, APP_SECRET)
# print(f'[file:{__file__}]=>[line:{(sys._getframe().f_lineno)
#   }]==>[tenant_access_token:{tenant_access_token}]')

# 以下两句代码建议同时使用，每次都获取token，避免token过期
tenant_access_token = app.tenant_access_token()
table = FS_Table(tenant_access_token, APP_TOKEN, TABLE_ID)


# print(table)


def add_record(fields):
    data1 = table.add(fields)
    print(data1)


def main():

    # ✅新增记录
    fidels = {
        "ID": "1",
        "key": "key",
        "value": "value",
    }
    data1 = table.add(fidels)
    print(data1)

    # ✅查询记录
    data2 = table.where([
        {
            "field_name": "ID",
            "operator": "is",
            "value": ["1"]
        }
    ]).get()
    print(data2)

    # ✅简单查询
    data3 = table.where([
        {
            "field_name": "ID",
            "value": ["1"]
        }
    ]).get()
    print(data3)

    # ✅删除记录 where查询后有多条记录 则.remove会把多条记录删除
    data4 = table.where([
        {
            "field_name": "value",
            "value": ["new value"]
        }
    ]).remove()

    print(data4)

    # ✅update
    data5 = table.where([
        {
            "field_name": "ID",
            "value": [1]
        }
    ]).update({
        "value": "new value"
        # "字段"："新值"
    })

    print(data5)

    copyright = 'ddddnet@github'


if __name__ == "__main__":
    # main()

    # 新增记录
    # fields = {
    #     "VIN": "00000678901234567",
    #     "结果": "OK",
    # }
    # add_record(fields)

    # 查询记录
    data = table.where([]).get()
    print(data)
    # print("================================================")
    # data = table.where([]).get()
    # print(data)

    # 删除记录
    # res = table.where(
    #     [{"field_name": "VIN", "operator": "is", "value": ["00000678901234567"]}]).remove()
    # print(res)
    pass
